package win.larry.test;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public class MyTest_1 {
	@Test
	public void run() throws ClientProtocolException, IOException {
		String proxy = "";
		String asString = Request.Get("http://www.baidu.com").connectTimeout(1000).socketTimeout(1000).execute().returnContent()
				.asString(Charset.forName("utf8"));
		System.out.println(asString);
	}

	@Test
	public void run1() throws ClientProtocolException, IOException {
		int code = Request.Get("http://www.baidu.com").connectTimeout(3000).socketTimeout(3000).execute().returnResponse().getStatusLine()
				.getStatusCode();
		System.out.println(code);
	}

	@Test
	public void run3() throws ClientProtocolException, IOException {
		int code = Request.Get("http://www.baidu.com").connectTimeout(3000).socketTimeout(3000).viaProxy("27.213.248.72:8888").execute()
				.returnResponse().getStatusLine().getStatusCode();
		System.out.println(code);
	}

	@Test
	public void run4() throws ClientProtocolException, IOException {
		HttpResponse httpResponse = Request.Get("http://baiduxxdgasdga.com")
				./* connectTimeout(3000).socketTimeout(3000). */viaProxy("210.136.142.240:8080").execute().returnResponse();
		Arrays.asList(httpResponse.getAllHeaders()).forEach(e -> {
			System.out.println(e);
		});
		System.out.println(httpResponse.getStatusLine());
		System.out.println(EntityUtils.toString(httpResponse.getEntity()));
	}

	@SuppressWarnings("deprecation")
	@Test
	public void run5() throws ClientProtocolException, IOException {

		CloseableHttpClient client = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler())
				.setProxy(HttpHost.create("210.136.142.240:8080")).build();
		HttpGet req = new HttpGet("http://www.baidu.com");
		// RequestConfig config = RequestConfig.custom().build();
		// req.setConfig(config);
		CloseableHttpResponse res = client.execute(req);
		// 响应体
		HttpEntity entity = res.getEntity();
		String string = EntityUtils.toString(entity);
		System.out.println(string);
		Arrays.asList(res.getAllHeaders()).forEach(e -> {
			System.out.println(e);
		});
		System.out.println(res.getStatusLine());
		System.out.println(res.getLocale());
	}

	@Test
	public void run6() throws IOException {

		URL url = new URL("http://www.baidu.com");
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("210.136.142.240", 8080));
		HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
		conn.setConnectTimeout(15000);
		conn.setReadTimeout(15000);

		conn.setRequestMethod("GET");
		conn.connect();

		System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		int responseCode = conn.getResponseCode();
		System.out.println(responseCode);
		String responseMessage = conn.getResponseMessage(); //
		System.out.println(responseMessage);
		// 输出内容，响应体。
		InputStream inputStream = conn.getInputStream();
		int len = 1024;
		byte[] bs = new byte[len];
		// List<byte[]> list = new ArrayList<>();
		int off = 0;
		while (off != -1) {
			off = inputStream.read(bs, 0, len);
			System.out.print("-----------" + new String(bs));
		}

		long contentLengthLong = conn.getContentLengthLong();
		String contentType = conn.getContentType();

		System.out.println(contentLengthLong);
		System.out.println(contentType);
	}

	@Test
	public void run7() throws IOException {

		URL url = new URL("http://www.baidu.com");
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("210.136.142.240", 8080));
		HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
		conn.setConnectTimeout(15000);
		conn.setReadTimeout(15000);

		conn.setRequestMethod("GET");
		conn.connect();

		System.out.println("!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		int responseCode = conn.getResponseCode();
		System.out.println(responseCode);
		String responseMessage = conn.getResponseMessage(); //
		System.out.println(responseMessage);
		// 输出内容，响应体。
		InputStream inputStream = conn.getInputStream();
		int len = 1024;
		byte[] bs = new byte[len];
		// List<byte[]> list = new ArrayList<>();
		int off = 0;
		// int available = inputStream.available();
		// System.out.println(available);

		// byte[] all = new byte[1024 * 1024 * 3];
		OutputStream os = new DataOutputStream(System.out);
		while (off != -1) {
			off = inputStream.read(bs, 0, len);
			if (off != -1)
				os.write(bs, 0, off);
			else
				os.flush();
			// System.out.print("-----------" + new String(bs));
		}
		os.close();
		inputStream.close();

		long contentLengthLong = conn.getContentLengthLong();
		String contentType = conn.getContentType();

		System.out.println(contentLengthLong);
		System.out.println(contentType);
	}

	/**
	 * 将输入流（响应），写入到字节数组输出流中，再保存为string，以便解析。
	 * 
	 * @throws IOException
	 */
	@Test
	public void run8() throws IOException {

		URL url = new URL("http://www.baidu.com");
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("210.136.142.240", 8080));
		HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
		conn.setConnectTimeout(15000);
		conn.setReadTimeout(15000);

		conn.setRequestMethod("GET");
		conn.connect();

		System.out.println("!!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		int responseCode = conn.getResponseCode();
		System.out.println(responseCode);
		String responseMessage = conn.getResponseMessage(); //
		System.out.println(responseMessage);

		System.out.println("!!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		// 输出内容，响应体。
		InputStream inputStream = conn.getInputStream();
		int len = 1024;
		byte[] bs = new byte[len];
		int off = 0;

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		while (off != -1) {
			off = inputStream.read(bs, 0, len);
			if (off != -1)
				baos.write(bs, 0, off);
			else
				baos.flush();
			// System.out.print("-----------" + new String(bs));
		}
		baos.close();
		inputStream.close();

		String str = baos.toString();
		System.out.println(str);
		System.out.println("!!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

		long contentLengthLong = conn.getContentLengthLong();
		String contentType = conn.getContentType();

		System.out.println(contentLengthLong);
		System.out.println(contentType);
	}

	/**
	 * 遍历所有header。
	 * 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@Test
	public void run12() throws ClientProtocolException, IOException {
		HttpResponse response = Request.Get("http://www.baidu.com").connectTimeout(3000).socketTimeout(3000).execute().returnResponse();
		HeaderIterator headerIterator = response.headerIterator();
		while (headerIterator.hasNext()) {
			System.out.println(headerIterator.next());
		}

		String domain = "";
		Header[] headers = response.getHeaders("Set-Cookie");
		for (Header header : headers) {
			System.out.println(header);
			String[] split = header.getValue().split(";");
			for (String string : split) {
				if (string.toLowerCase().contains("domain")) {
					domain = string;
					break;
				}
			}
		}

		System.out.println(" --- " + domain);
	}

	@Test
	public void run2() {
		HttpHost host = HttpHost.create("128.0.0.1:8080");
		System.out.println(host);
		System.out.println(host.getPort()); // 8080
		System.out.println(host.getSchemeName()); // http
		System.out.println(host.getHostName()); // 128.0.0.1
	}
}
